package com.gavinandre.mvpsocketclient.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.gavinandre.mvpsocketclient.R;
import com.gavinandre.socket.ClientTarget;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class SocketClientActivity extends AppCompatActivity implements ClientTarget.OnUpdataListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_demo);
        init();

        new Thread(new Runnable() {
            @Override
            public void run() {
                initView();
            }
        }).start();


    }
    Button  send;
    TextView textView;
    EditText editText;
    private void init( ) {

        send = findViewById(R.id.button_server_id);

        textView = findViewById(R.id.textview_server);

        editText = findViewById(R.id.edit_server_input);


    }

    private void initView() {
        Socket socket = null;
        PrintWriter pw = null;
        Scanner scan = null;
        try {
            //创建客户端  127.0.0.1 = localhost
            socket = new Socket("192.168.31.168",10086);
            System.out.println("连接成功!");


            //开启一个子线程，用于自动接收服务端发来的消息
            ClientTarget ct = new ClientTarget(socket);
            ct.setOnUpdataListener(this);
            Thread t = new Thread(ct);
            t.start();

            //获取客户端的键盘监听
            scan = new Scanner(System.in);
            //创建用于发送消息的字符打印流
            pw = new PrintWriter(socket.getOutputStream(), true);//自动刷新

            while(true){
                System.out.println("请输入消息内容：");
              //  String clientMsg = scan.nextLine();
               String clientMsg = editText.getText().toString().trim();
                pw.println(clientMsg);//发送消息

            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            try {
            //    pw.close();
              //  scan.close();
            //    socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //拿到了客户端发来的消息
    @Override
    public void upDataUI(String message) {

        textView.setText(message);

    }
}
